/**
 * 全局设置状态管理
 * 
 * 管理应用的主题、语言等全局设置
 */

import { ref, computed, watch } from 'vue'

// 主题类型
export type ThemeType = 'light' | 'dark' | 'auto'

// 颜色主题类型
export type ColorThemeType = 'blue' | 'green' | 'purple' | 'orange' | 'red' | 'teal' | 'pink' | 'indigo'

// 语言类型  
export type LanguageType = 'zh-CN' | 'en-US'

// 设置状态
const theme = ref<ThemeType>('auto')
const colorTheme = ref<ColorThemeType>('blue')
const language = ref<LanguageType>('zh-CN')

// 从本地存储加载设置
const loadSettings = () => {
  try {
    const savedTheme = localStorage.getItem('app-theme') as ThemeType
    const savedColorTheme = localStorage.getItem('app-color-theme') as ColorThemeType
    const savedLanguage = localStorage.getItem('app-language') as LanguageType
    
    if (savedTheme && ['light', 'dark', 'auto'].includes(savedTheme)) {
      theme.value = savedTheme
    }
    
    if (savedColorTheme && ['blue', 'green', 'purple', 'orange', 'red', 'teal', 'pink', 'indigo'].includes(savedColorTheme)) {
      colorTheme.value = savedColorTheme
    }
    
    if (savedLanguage && ['zh-CN', 'en-US'].includes(savedLanguage)) {
      language.value = savedLanguage
    }
  } catch (error) {
    console.error('加载设置失败:', error)
  }
}

// 保存设置到本地存储
const saveSettings = () => {
  try {
    localStorage.setItem('app-theme', theme.value)
    localStorage.setItem('app-color-theme', colorTheme.value)
    localStorage.setItem('app-language', language.value)
  } catch (error) {
    console.error('保存设置失败:', error)
  }
}

// 应用主题到DOM
const applyTheme = (themeType: ThemeType, colorThemeType?: ColorThemeType) => {
  const root = document.documentElement
  
  // 移除现有主题类
  root.classList.remove('theme-light', 'theme-dark')
  root.classList.remove('color-blue', 'color-green', 'color-purple', 'color-orange', 'color-red', 'color-teal', 'color-pink', 'color-indigo')
  
  if (themeType === 'auto') {
    // 自动模式：根据系统主题决定
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
    root.classList.add(prefersDark ? 'theme-dark' : 'theme-light')
  } else {
    // 手动模式：直接应用指定主题
    root.classList.add(`theme-${themeType}`)
  }
  
  // 应用颜色主题
  const currentColorTheme = colorThemeType || colorTheme.value
  root.classList.add(`color-${currentColorTheme}`)
}

// 应用颜色主题
const applyColorTheme = (colorThemeType: ColorThemeType) => {
  const root = document.documentElement
  
  // 移除现有颜色主题类
  root.classList.remove('color-blue', 'color-green', 'color-purple', 'color-orange', 'color-red', 'color-teal', 'color-pink', 'color-indigo')
  
  // 应用新的颜色主题
  root.classList.add(`color-${colorThemeType}`)
}

// 当前实际主题（考虑auto模式）
const currentTheme = computed(() => {
  if (theme.value === 'auto') {
    return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
  }
  return theme.value
})

// 监听主题变化
watch(theme, (newTheme) => {
  applyTheme(newTheme)
  saveSettings()
}, { immediate: true })

// 监听颜色主题变化
watch(colorTheme, (newColorTheme) => {
  applyColorTheme(newColorTheme)
  saveSettings()
}, { immediate: true })

// 监听语言变化
watch(language, () => {
  saveSettings()
})

// 监听系统主题变化（仅在auto模式下生效）
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
  if (theme.value === 'auto') {
    applyTheme('auto')
  }
})

// 设置主题
export const setTheme = (newTheme: ThemeType) => {
  theme.value = newTheme
}

// 切换主题（在light和dark之间切换）
export const toggleTheme = () => {
  if (currentTheme.value === 'dark') {
    setTheme('light')
  } else {
    setTheme('dark')
  }
}

// 设置语言
export const setLanguage = (newLanguage: LanguageType) => {
  language.value = newLanguage
}

// 切换语言
export const toggleLanguage = () => {
  setLanguage(language.value === 'zh-CN' ? 'en-US' : 'zh-CN')
}

// 设置颜色主题
export const setColorTheme = (newColorTheme: ColorThemeType) => {
  colorTheme.value = newColorTheme
}

// 切换颜色主题（循环切换）
export const toggleColorTheme = () => {
  const colorThemes: ColorThemeType[] = ['blue', 'green', 'purple', 'orange', 'red', 'teal', 'pink', 'indigo']
  const currentIndex = colorThemes.indexOf(colorTheme.value)
  const nextIndex = (currentIndex + 1) % colorThemes.length
  setColorTheme(colorThemes[nextIndex])
}

// 初始化设置
export const initSettings = () => {
  loadSettings()
}

// 导出响应式状态
export const useSettings = () => {
  return {
    theme: computed(() => theme.value),
    currentTheme,
    colorTheme: computed(() => colorTheme.value),
    language: computed(() => language.value),
    setTheme,
    toggleTheme,
    setColorTheme,
    toggleColorTheme,
    setLanguage,
    toggleLanguage
  }
}
